package com.davidjmcclelland;

/****************************************************
 * Java tag handler class to convert Celsius to Fahrenheit
 * or Kelvin.
 *
 * Copyright 2005 by Arnold Doray
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *****************************************************/

import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.*;


public class Converter extends BodyTagSupport {

    private String _to = "";

    public int doAfterBody() {
        try {
            BodyContent bc = getBodyContent();
            // parse the temp value from body content passed in via tag contents
            double temperature = Double.parseDouble(bc.getString());
            // evaluate
            if (_to == null || _to.length() == 0 || _to.toUpperCase().startsWith("F")) {
                bc.getEnclosingWriter().print(toFahrenheit(temperature));
            } else {
                bc.getEnclosingWriter().print(toKelvin(temperature));
            }

        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
        /***** PUT IN YOUR IMPLEMENTATION HERE *****/

        return EVAL_PAGE; //tells servlet container to process rest of JSP page.
    }

    private double toFahrenheit(double c) {
        return 32.0 + (c * 1.8);
    }

    private double toKelvin(double c) {
        return 273.0 + c;
    }

    /**
     * Get and Set methods expected by the servlet container
     */
    public String getTo() {
        return _to;
    }

    public void setTo(String to) {
        _to = to;
    }
}